//
//  CalenViewController.m
//  JiaoWuGuanLi
//
//  Created by Zinzie on 14-4-2.
//  Copyright (c) 2014年 Zinzie. All rights reserved.
//

#import "CalenViewController.h"
#import "MainInterfaceAppDelegate.h"
#import "CalDataModelController.h"

@interface CalenViewController ()<UIScrollViewDelegate>
{

    int preButtonAtIndex;
    int weekNow;
    int todayButton;
    BOOL firstLoad;
    BOOL reallyNeedScroll;
    
}

@property (weak, nonatomic) IBOutlet UILabel *LabelWeek;

@property (weak, nonatomic) IBOutlet UIButton *buttonNextWeek;
@property (weak, nonatomic) IBOutlet UIButton *buttonPreWeek;

@property (weak, nonatomic) IBOutlet UIButton *button1;
@property (weak, nonatomic) IBOutlet UIButton *button2;
@property (weak, nonatomic) IBOutlet UIButton *button3;
@property (weak, nonatomic) IBOutlet UIButton *button4;
@property (weak, nonatomic) IBOutlet UIButton *button5;
@property (weak, nonatomic) IBOutlet UIButton *button6;
@property (weak, nonatomic) IBOutlet UIButton *button7;
@property (strong,nonatomic) NSArray *buttons;
@property (strong,nonatomic) CalDataModelController *dataController;
@property (weak, nonatomic) IBOutlet UIButton *todayButton;
@property (nonatomic) int weekCount;

@property (nonatomic)  int currentButtonAtIndex;

@property (weak, nonatomic) IBOutlet UIView *bgdView;


@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITableView *tableViewMon;
@property (weak, nonatomic) IBOutlet UITableView *tableViewTue;
@property (weak, nonatomic) IBOutlet UITableView *tableViewWed;
@property (weak, nonatomic) IBOutlet UITableView *tableViewThu;
@property (weak, nonatomic) IBOutlet UITableView *tableViewFir;
@property (weak, nonatomic) IBOutlet UITableView *tableViewSat;
@property (weak, nonatomic) IBOutlet UITableView *tableViewSun;


@end

@implementation CalenViewController
@synthesize todayButton = _todayButton;

#pragma mark - init
-(void)setWeekCount:(int)weekCount{
    _weekCount = weekCount;
    self.dataController.week = _weekCount;
    [self allTableViewReload];
}

-(void)setCurrentButtonAtIndex:(int)currentButtonAtIndex{
    NSLog(@"hooooooooooooooo");

        _currentButtonAtIndex=currentButtonAtIndex;
/*
        if (currentButtonAtIndex==0) {
            self.dataController.xingqi = 7;
        }
        else {
        self.dataController.xingqi = currentButtonAtIndex;
        }
 */
    //[self allTableViewReload];
}



-(UIBarButtonItem *)leftNoDisplay{
    if (!_leftNoDisplay) {
        _leftNoDisplay = [[UIBarButtonItem alloc]initWithTitle:@"未登录"
                                                         style:UIBarButtonItemStyleBordered
                                                        target:self
                                                        action:@selector(noDisplay)];
        //        self.navigationItem.leftBarButtonItem = _leftNoDisplay;
        
    }
    return _leftNoDisplay;
}

-(void)setDengLuXueHao:(NSString *)dengLuXueHao{
    _dengLuXueHao = dengLuXueHao;
    if (_dengLuXueHao!=nil) {
        self.leftNoDisplay.title = _dengLuXueHao;
    }
    else{
        self.leftNoDisplay.title = @"未登录";
    }
    
}
-(UIBarButtonItem *)rightButton{
    if (!_rightButton) {
        _rightButton = [[UIBarButtonItem alloc]initWithTitle:@"今天" style:UIBarButtonItemStyleBordered target:self action:@selector(backToToday)];
                        }
    return _rightButton;
}
-(void)noDisplay{
    
}

-(void)backToToday{
    while ((self.weekCount-weekNow)!=0) {
        if (self.weekCount-weekNow>0) {
            [self prePressed];
        }
        else if (self.weekCount-weekNow<0){
            [self nextPressed];
        }}
    
    NSDate *date = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSUInteger unitFlags1 = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *dayComponent = [cal components:unitFlags1 fromDate:date];
    preButtonAtIndex = self.currentButtonAtIndex;
    self.currentButtonAtIndex = [dayComponent weekday]-1;
    [self.scrollView scrollRectToVisible:CGRectMake(320*([dayComponent weekday]-1), 0, 320, 352) animated:NO];
    NSLog(@"backkkkkkkkkkk");

    todayButton = self.currentButtonAtIndex;
    [self setbgd];
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = self.leftNoDisplay;
    self.navigationItem.rightBarButtonItem = self.rightButton;
    self.buttons = @[self.button1,self.button2,self.button3,self.button4,self.button5,self.button6,self.button7];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndRefresh) name:@"ShuXinClassesOK" object:self.dataController];
    // Do any additional setup after loading the view.
    self.dataController=[[CalDataModelController alloc]init];
//    [self.dataController acquireData];
    [self initWeekCount];
    [self initCurrentButton];
    [self setDate];
    [self setLabel];
    [self.scrollView setDelegate:self];                                             //delegate!!!!!!
    reallyNeedScroll = NO;
    firstLoad = YES;
}
-(void)viewWillAppear:(BOOL)animated{
    MainInterfaceAppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    self.dengLuXueHao=myDelegate.userName;
    [self.todayButton setBackgroundImage:[UIImage imageNamed:@"redDot"] forState:UIControlStateNormal];
    self.scrollView.frame = CGRectMake(0, 166, 320, 352);
    self.scrollView.contentSize = CGSizeMake(2240, 352);
    [super viewWillAppear:animated];
}

-(void)viewDidAppear:(BOOL)animated{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([[defaults objectForKey:@"online"] boolValue]) {
        NSLog(@"acquire data");
        [self.dataController acquireData];
    }
    self.scrollView.frame = CGRectMake(0, 166, 320, 352);
    self.scrollView.contentSize = CGSizeMake(2240, 352);
    self.scrollView.directionalLockEnabled = YES;
    self.scrollView.alwaysBounceVertical = NO;
    [super viewDidAppear:animated];
        [self setbgd];
    UIButton *tempbut = [self.buttons objectAtIndex:todayButton];
    CGPoint temp = tempbut.center;
    temp.y = temp.y + 20;
    self.todayButton.center = temp;
    [self allTableViewReload];
    [self performSelector:@selector(KebiaoRefresh) withObject:self afterDelay:0.5];
    if (firstLoad) {
        [self.scrollView scrollRectToVisible:CGRectMake((320*todayButton), 0, 320, 352) animated:NO];
        firstLoad = NO;
        
    }if([[[UIDevice currentDevice] systemVersion] floatValue]<8.0 ){
        NSLog(@"fucking want shit!!!");
        reallyNeedScroll = YES;
        [self dayPressed:[self.buttons objectAtIndex:self.currentButtonAtIndex]];
        }

}

//-(void)viewDidDisappear:(BOOL)animated{
//    [super viewDidDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ShuXinClassesOK" object:self.dataController];
//
//}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ShuXinClassesOK" object:self.dataController];

}
-(void)didEndRefresh{
    NSLog(@"did end refresh %d",self.dataController.thu.count);
    [self allTableViewReload];
}
-(void)allTableViewReload{
    [self.tableViewMon reloadData];
    [self.tableViewTue reloadData];
    [self.tableViewWed reloadData];
    [self.tableViewThu reloadData];
    [self.tableViewFir reloadData];
    [self.tableViewSat reloadData];
    [self.tableViewSun reloadData];
}
-(void)KebiaoRefresh{
    self.currentButtonAtIndex = self.currentButtonAtIndex;
}
-(void)initCurrentButton{
    NSDate *date = [NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSUInteger unitFlags1 = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *dayComponent = [cal components:unitFlags1 fromDate:date];
    self.currentButtonAtIndex = [dayComponent weekday]-1;
    preButtonAtIndex = self.currentButtonAtIndex;
    todayButton = self.currentButtonAtIndex;
    NSLog(@"123123 %d",[dayComponent weekday]-1);
}

-(void)initWeekCount{
    //init weekcount
    NSDate *date = [NSDate date];
    NSDateComponents *comps  = [[NSDateComponents alloc] init];
    [comps setDay:7];
    [comps setMonth:9];
    [comps setYear:2015];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *StartDate = [gregorian dateFromComponents:comps];
    int initunitFlags = NSDayCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *resultComps = [gregorian components:initunitFlags fromDate:StartDate  toDate:date  options:0];
    self.weekCount =  [resultComps day]/7+1;
    if (_weekCount < 1) {
        _weekCount = 1;
    }
//    if (self.weekCount>=1) {
//        weekNow = self.weekCount;
//    }
    weekNow = self.weekCount;

}
-(void)setLabel{
    self.LabelWeek.text = [NSString stringWithFormat:@"%d",self.weekCount];
}

-(void)setDate{
    NSDate *date = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate: date];
//    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
//    NSLog(@"%@", localeDate);
//
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:date];
    int year = [dateComponent year];
    int month = [dateComponent month];
    int day = [dateComponent day];
    int hour = [dateComponent hour];
    int minute = [dateComponent minute];
    int second = [dateComponent second];
    int weekday = [dateComponent weekday];
    
    NSLog(@"year is: %d", year);
    NSLog(@"month is: %d", month);
    NSLog(@"day is: %d", day);
    NSLog(@"hour is: %d", hour);
    NSLog(@"minute is: %d", minute);
    NSLog(@"second is: %d", second);
    NSLog(@"weekday is %d",weekday);
    NSLog(@"what the hell");
    NSLog(@"%d",weekNow);
    
    for (int i=1; i<8; i++) {//i 为周几
        if (weekday == i) {
            for (int n = 0; n<7; n++) {//7个button
                //NSLog(@"i=%d,n=%d",i,n);
            NSDate *temp =[NSDate dateWithTimeIntervalSinceNow:(7*(self.weekCount-weekNow)-i+1+n)*24*60*60];
               // NSLog(@"%@",temp);
            NSUInteger unitFlag = NSDayCalendarUnit;
            NSDateComponents *date = [[NSCalendar currentCalendar] components:unitFlag fromDate:temp];
            UIButton *tempButton = [self.buttons objectAtIndex:n];
            [tempButton setTitle:[NSString stringWithFormat:@"%d",[date day]] forState:UIControlStateNormal];
            
            }
            
        }
    }


}
- (IBAction)prePressed {
    if (self.weekCount>1) {
        self.weekCount--;
        [self setLabel];
        [self setDate];
        [self todayOrNot];
    }
}

- (IBAction)nextPressed {
    self.weekCount++;
    [self setLabel];
    [self setDate];
    [self todayOrNot];

}

-(void)todayOrNot{
    if (self.weekCount-weekNow==0) {
        self.todayButton.hidden=NO;
    }else{
        self.todayButton.hidden=YES;
    }
}


#pragma mark - day bgdView
-(void)setbgd{
    NSLog(@"pre:%d,current:%d",preButtonAtIndex,self.currentButtonAtIndex);
        UIButton *tempBut = [self.buttons objectAtIndex:preButtonAtIndex];//preButton设置
        tempBut.tintColor = self.bgdView.backgroundColor;
        tempBut = [self.buttons objectAtIndex:self.currentButtonAtIndex];//currentButton设置

    [UIView animateWithDuration:0.2
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         self.bgdView.center = tempBut.center;
                         tempBut.tintColor = [UIColor whiteColor];
                     }
                     completion:^(BOOL finished) {
                     }];
    
    //[self allTableViewReload];
}

- (IBAction)dayPressed:(UIButton *)sender {
    for (int i=0; i<7; i++) {
        if (sender == [self.buttons objectAtIndex:i] && (sender!= [self.buttons objectAtIndex:self.currentButtonAtIndex]|| reallyNeedScroll)) {
            preButtonAtIndex = self.currentButtonAtIndex;
            self.currentButtonAtIndex = i;
            NSLog(@"dayyyyyyyyyyyyy pressed");
            [self.scrollView scrollRectToVisible:CGRectMake((320*i), 0, 320, 352) animated:NO];

        }
    }
    if (reallyNeedScroll) {
        reallyNeedScroll = NO;
    }
    [self setbgd];

}

//- (IBAction)swipeRight:(UISwipeGestureRecognizer *)sender {
//    if (self.currentButtonAtIndex != 0) {
//    preButtonAtIndex = self.currentButtonAtIndex;
//    self.currentButtonAtIndex--;
//    [self setbgd];
//    }
//}
//
//- (IBAction)swipeLeft:(id)sender {
//    if (self.currentButtonAtIndex !=6) {
//        
//    preButtonAtIndex = self.currentButtonAtIndex;
//    self.currentButtonAtIndex++;
//    [self setbgd];
//    }
//}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.scrollView) {
        NSLog(@"offset of scrollView is %f",scrollView.contentOffset.x);
        CGFloat pageWidth = scrollView.frame.size.width;
        NSInteger page = scrollView.contentOffset.x / pageWidth;
        
        NSLog(@"the page is %d,%d",page,self.currentButtonAtIndex);
        preButtonAtIndex = self.currentButtonAtIndex;
        self.currentButtonAtIndex=page;
        [self setbgd];
    }
}
#pragma mark - class table

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==self.tableViewMon){
        if ([self.dataController.mon count]) return [self.dataController.mon count];
        else return 1;
    }else if (tableView==self.tableViewTue){
        if ([self.dataController.tue count]) return [self.dataController.tue count];
        else return 1;
    }else if (tableView==self.tableViewWed){
        if ([self.dataController.wed count]) return [self.dataController.wed count];
        else return 1;
    }else if (tableView==self.tableViewThu){
        if ([self.dataController.thu count]) return [self.dataController.thu count];
        else return 1;
    }else if (tableView==self.tableViewFir){
        if ([self.dataController.fri count]) return [self.dataController.fri count];
        else return 1;
    }else if (tableView==self.tableViewSat){
        if ([self.dataController.sat count]) return [self.dataController.sat count];
        else return 1;
    }else {
        if ([self.dataController.sun count]) return [self.dataController.sun count];
        else return 1;
    }
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
}

-(UITableViewCell *)dealDataAndOutpuCell:(UITableView *)tableView
                                    data:(NSMutableArray *)classArray
                         cellAtIndexPath:(NSIndexPath *)indexPath{
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"classCell"];
    
    static NSString *CellIdentifier = @"classCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UILabel *timeStart = (UILabel *)[cell viewWithTag:1];
    UILabel *timeEnd = (UILabel *)[cell viewWithTag:2];
    UILabel *name = (UILabel *)[cell viewWithTag:3];
    UILabel *teacher = (UILabel *)[cell viewWithTag:4];
    UILabel *location = (UILabel *)[cell viewWithTag:5];
    UILabel *noClasses = (UILabel *)[cell viewWithTag:6];
    
    if ([classArray count]) {
        NSLog(@"jlsajflasjfla;");
        
        //    UILabel *label = (UILabel *)[cell viewWithTag:1];
        
        CalDataModel *model = [classArray objectAtIndex:indexPath.row];
        
        timeStart.hidden=NO;
        timeEnd.hidden=NO;
        name.hidden=NO;
        teacher.hidden=NO;
        location.hidden=NO;
        noClasses.hidden=YES;
        
        name.text=model.mingCheng;
        teacher.text=model.laoShi;
        location.text=model.jiaoShi;
       // NSLog(@"上课时间为%@",model.shiJian);
        if ([model.shiJian isEqualToString:@"1"]) {
            timeStart.text = @"8:00";
            timeEnd.text = @"9:35";
        }else if ([model.shiJian isEqualToString:@"2"]){
            timeStart.text = @"9:55";
            timeEnd.text = @"11:30";
        }else if ([model.shiJian isEqualToString:@"3"]){
            timeStart.text = @"13:30";
            timeEnd.text = @"15:05";
        }else if ([model.shiJian isEqualToString:@"4"]){
            timeStart.text = @"15:25";
            timeEnd.text = @"17:00";
        }else if ([model.shiJian isEqualToString:@"5"]){
            timeStart.text = @"18:00";
            timeEnd.text = @"19:35";
        }else if ([model.shiJian isEqualToString:@"6"]){
            timeStart.text = @"19:55";
            timeEnd.text = @"21:30";
        }
        
        
        /*    [[cell textLabel] setText:dataAtIndex.name];
         [[cell detailTextLabel] setText:dataAtIndex.mark];
         */
        return cell;
        
    }
    else{
        timeStart.hidden=YES;
        timeEnd.hidden=YES;
        name.hidden=YES;
        teacher.hidden=YES;
        location.hidden=YES;
        noClasses.hidden=NO;
        return cell;
    }

    
    return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.tableViewMon) {
        return [self dealDataAndOutpuCell:tableView data:self.dataController.mon cellAtIndexPath:indexPath];
    }else if (tableView==self.tableViewTue){
        return [self dealDataAndOutpuCell:tableView data:self.dataController.tue cellAtIndexPath:indexPath];
    }else if (tableView==self.tableViewWed){
        return [self dealDataAndOutpuCell:tableView data:self.dataController.wed cellAtIndexPath:indexPath];
    }else if (tableView==self.tableViewThu){
        return [self dealDataAndOutpuCell:tableView data:self.dataController.thu cellAtIndexPath:indexPath];
    }else if (tableView==self.tableViewFir){
        return [self dealDataAndOutpuCell:tableView data:self.dataController.fri cellAtIndexPath:indexPath];
    }else if (tableView==self.tableViewSat){
        return [self dealDataAndOutpuCell:tableView data:self.dataController.sat cellAtIndexPath:indexPath];
    }else
        return [self dealDataAndOutpuCell:tableView data:self.dataController.sun cellAtIndexPath:indexPath];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
